package org.zwy.gradetrack.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;
import org.zwy.gradetrack.entity.GraduationRequirementAchievement;
import org.zwy.gradetrack.entity.Indicator;
import org.zwy.gradetrack.service.GraduationRequirementAchievementService;
import org.zwy.gradetrack.service.IndicatorService;
import org.zwy.gradetrack.vo.GraduationRequirementAchievementVo;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

/**
 * 毕业要求达成度管理控制器
 */
@RestController
@RequestMapping("/api/graduation-requirement-achievements")
public class GraduationRequirementAchievementController {

    @Autowired
    private GraduationRequirementAchievementService graduationRequirementAchievementService;

    @Autowired
    private IndicatorService indicatorService;

    /**
     * 获取达成度列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER','GRADUATE')")
    public Result<List<GraduationRequirementAchievementVo>> getAchievementList(
            @RequestParam(required = false) Integer evaluationYear) {
        List<GraduationRequirementAchievementVo> achievements = graduationRequirementAchievementService.getAchievementVos(evaluationYear);
        return Result.success(achievements);
    }

    /**
     * 创建达成度
     */
    @PostMapping
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<GraduationRequirementAchievement> createAchievement(@RequestBody GraduationRequirementAchievement achievement) {
        // 检查指标点是否存在
        if (!indicatorService.lambdaQuery()
                .eq(Indicator::getId, achievement.getIndicatorId())
                .exists()) {
            return Result.error(404, "指标点不存在");
        }

        // 检查是否已存在相同指标点、评价年份的记录
        if (graduationRequirementAchievementService.lambdaQuery()
                .eq(GraduationRequirementAchievement::getIndicatorId, achievement.getIndicatorId())
                .eq(GraduationRequirementAchievement::getEvaluationYear, achievement.getEvaluationYear())
                .exists()) {
            return Result.error(400, "该指标点在指定评价年份的达成度记录已存在");
        }

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        achievement.setCreateTime(now);
        achievement.setUpdateTime(now);

        // 计算综合评价值并判断是否达成
        graduationRequirementAchievementService.calculateComprehensiveScore(achievement);

        // 保存达成度信息
        graduationRequirementAchievementService.save(achievement);
        return Result.success(achievement);
    }

    /**
     * 更新达成度
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<GraduationRequirementAchievement> updateAchievement(@PathVariable Long id, @RequestBody GraduationRequirementAchievement achievement) {
        // 检查达成度是否存在
        if (!graduationRequirementAchievementService.lambdaQuery()
                .eq(GraduationRequirementAchievement::getId, id)
                .exists()) {
            return Result.error(404, "达成度不存在");
        }

        // 检查指标点是否存在
        if (!indicatorService.lambdaQuery()
                .eq(Indicator::getId, achievement.getIndicatorId())
                .exists()) {
            return Result.error(404, "指标点不存在");
        }

        // 检查是否与其他记录冲突
        if (graduationRequirementAchievementService.lambdaQuery()
                .eq(GraduationRequirementAchievement::getIndicatorId, achievement.getIndicatorId())
                .eq(GraduationRequirementAchievement::getEvaluationYear, achievement.getEvaluationYear())
                .ne(GraduationRequirementAchievement::getId, id)
                .exists()) {
            return Result.error(400, "该指标点在指定评价年份的达成度记录已存在");
        }

        // 更新达成度信息
        achievement.setId(id);
        achievement.setUpdateTime(LocalDateTime.now());

        // 计算综合评价值并判断是否达成
        graduationRequirementAchievementService.calculateComprehensiveScore(achievement);

        graduationRequirementAchievementService.updateById(achievement);
        return Result.success(achievement);
    }

    /**
     * 删除达成度
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Void> deleteAchievement(@PathVariable Long id) {
        // 检查达成度是否存在
        if (!graduationRequirementAchievementService.lambdaQuery()
                .eq(GraduationRequirementAchievement::getId, id)
                .exists()) {
            return Result.error(404, "达成度不存在");
        }

        // 删除达成度
        graduationRequirementAchievementService.removeById(id);
        return Result.success();
    }

    /**
     * 获取达成度详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<GraduationRequirementAchievement> getAchievementDetail(@PathVariable Long id) {
        GraduationRequirementAchievement achievement = graduationRequirementAchievementService.getById(id);
        if (achievement == null) {
            return Result.error(404, "达成度不存在");
        }
        return Result.success(achievement);
    }

    @GetMapping("/years")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER', 'GRADUATE')")
    public Result<List<Integer>> getYears() {
        return Result.success(graduationRequirementAchievementService.getEvaluationYears());
    }

    @GetMapping("/export")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER', 'GRADUATE')")
    public ResponseEntity<byte[]> exportToExcel(
            @RequestParam(required = false) Integer evaluationYear) throws IOException {
        byte[] excelBytes = graduationRequirementAchievementService.exportToExcel(evaluationYear);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "graduation_requirement_achievement.xlsx");
        headers.setContentLength(excelBytes.length);

        return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
    }
} 